#!/usr/bin/env python3

import os
import json
import logging
import argparse
from pprint import pprint
import traceback
import threading

import system
import ascii_art.ascii_shape as ascii_art


logger = logging.getLogger(__name__)


def _excepthook(args):
    '''args
    exc_type: Exception type.
    exc_value: Exception value, can be None.
    exc_traceback: Exception traceback, can be None.
    thread: Thread which raised the exception, can be None.
    '''
    traceback.print_exc()
    os._exit(1)


threading.excepthook = _excepthook


if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG)

    parser = argparse.ArgumentParser()
    parser.add_argument('--host', type=str, default='localhost', help='default: localhost')
    parser.add_argument('--port', type=int, default=9527, help='default: 9527')
    args = parser.parse_args()

    cur_path = os.path.dirname(os.path.abspath(__file__))
    db_path = os.path.join(cur_path, 'data', 'z.db.sqlite3')

    master = system.master.Master()
    master.DEBUG = True
    master.system = system
    master.ascii_art = ascii_art
    master.host = (args.host, args.port)
    master.db_path = db_path

    if not master.init():
        logger.fatal('maser init faild')
        os._exit(1)

    while(True):
        cmd = input('> ')
        if not cmd: continue

        if cmd in ('shutdown', 'quit', 'exit'): break

        if cmd in ('info',):
            pprint(vars(args))
        if cmd in ('save all',):
            master.save_db()
        else:
            try:
                ob = eval(cmd)
                if hasattr(ob, '__dict__'):
                    pprint(ob.__dict__)
                else:
                    pprint(ob)
            except:
                traceback.print_exc()
                print(f'unknown cmd: {cmd}')

